package icu.jiapeng.DemoJava.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import icu.jiapeng.DemoJava.entity.Request;
import icu.jiapeng.DemoJava.mapper.RequestMapper;
import icu.jiapeng.DemoJava.service.RequestService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Service
public class RequestServiceImpl extends ServiceImpl<RequestMapper, Request> implements RequestService {

    @Override
    public Request saveRequest(HttpServletRequest request, String body, Map<String, Object> params) {
        Enumeration<String> headerNames = request.getHeaderNames();
        HashMap<String, Object> headers = new HashMap<>();
        //遍历headerNames
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
            headers.put(key, value);
        }
        Request request1 = Request.builder()
                .body(body)
                .ip(request.getRemoteAddr())
                .userAgent(request.getHeader("User-Agent"))
                .cookie(request.getHeader("Cookie"))
                .header(JSONObject.toJSONString(headers))
                .api(request.getRequestURI())
                .method(request.getMethod())
                .query(JSONArray.toJSONString(params))
                .url(request.getRequestURL().toString())
                .build();
        save(request1);
        return request1;
    }
}
